//首先我们将导入 ESP8266WiFi 和 PubSubClient 库，ESP8266WiFi 库能够将 ESP8266 连接到 Wi-Fi 网络，PubSubClient 库能使 ESP8266 连接到 MQTT 服务器发布消息及订阅主题
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include “DFRobot_DHT11.h”
设置 Wi-Fi 名称和密码，以及 MQTT 服务器连接地址和端口
// WiFi
const char *ssid = “602iot”; // Enter your WiFi name
const char *password = “18wulian”; // Enter WiFi password
//设置 MQTT Broker 信息
// MQTT Broker
const char *mqtt_broker = “gb779e9e.cn.emqx.cloud”;
const char *topic = “zhong/a”;
const char *mqtt_username = “zyl”;
const char *mqtt_password = “123456”;
const int mqtt_port = 11062;

// DHT11
#define DHT11_PIN D4
unsigned long previousMillis = 0;

WiFiClient espClient;
PubSubClient client(espClient);
DFRobot_DHT11 DHT;
//打开一个串行连接，以便于输出程序的结果并且连接到 Wi-Fi 网络
void setup() {
// Set software serial baud to 115200;
Serial.begin(115200);
// connecting to a WiFi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println(“Connecting to WiFi…”);
}
Serial.println(“Connected to the WiFi network”);
//connecting to a mqtt broker
client.setServer(mqtt_broker, mqtt_port);
//connecting to a mqtt broker
while (!client.connected()) {
String client_id = “esp8266-client-”;
client_id += String(WiFi.macAddress());
Serial.printf(“The client %s connects to the public mqtt broker\n”, client_id.c_str());
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
Serial.println(“Public emqx mqtt broker connected”);
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}

}

void loop() {
client.loop();
unsigned long currentMillis = millis();
// temperature and humidity data are publish every five second
if (currentMillis - previousMillis >= 5000) {
previousMillis = currentMillis;
DHT.read(DHT11_PIN);//DHT11读取环境的温湿度数据
float temp = DHT.temperature;
float hum = DHT.humidity;
// json serialize 读取温湿度传感器数据以 json 格式上报数据
DynamicJsonDocument data(256);
data[“temp”] = temp;
data[“hum”] = hum;
// publish temperature and humidity
char json_string[256];
serializeJson(data, json_string);
// {“temp”:23.5,“hum”:55}
Serial.println(json_string);
client.publish(topic, json_string, false);
}
}
